package com.zhuliwei.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhuliwei.constants.SystemConstants;
import com.zhuliwei.domain.ResponseResult;
import com.zhuliwei.domain.dto.CommentListDto;
import com.zhuliwei.domain.entity.Article;
import com.zhuliwei.domain.entity.Comment;
import com.zhuliwei.domain.entity.User;
import com.zhuliwei.domain.vo.CommentListVo;
import com.zhuliwei.domain.vo.CommentVo;
import com.zhuliwei.domain.vo.PageVo;
import com.zhuliwei.enums.AppHttpCodeEnum;
import com.zhuliwei.exception.SystemException;
import com.zhuliwei.mapper.ArticleMapper;
import com.zhuliwei.mapper.CommentMapper;
import com.zhuliwei.service.CommentService;
import com.zhuliwei.service.UserService;
import com.zhuliwei.utils.BeanCopyUtils;
import com.zhuliwei.utils.SecurityUtils;
import com.zhuliwei.utils.SensitivewordFilter;
import jakarta.annotation.Resource;
import net.dreamlu.mica.ip2region.core.Ip2regionSearcher;
import net.dreamlu.mica.ip2region.core.IpInfo;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;

/**
 * 评论表(Comment)表服务实现类
 *
 * @author 朱力维
 * @since 2022-10-19 20:18:29
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {
    @Resource
    private UserService userService;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private Ip2regionSearcher ip2regionSearcher;

    @Resource
    private ArticleMapper articleMapper;

    //敏感词过滤工具类
    @Resource
    private SensitivewordFilter sensitivewordFilter;

    @Override
    public ResponseResult commentList(String type, String articleId, Integer pageNum, Integer pageSize) {
        //查询对应文章的根评论
        //对articleId进行判断
        LambdaQueryWrapper<Comment> lqw = new LambdaQueryWrapper<>();
        //评论必须是审核已通过的
        lqw.eq(Comment::getStatus, SystemConstants.COMMENT_NORMAL);
        lqw.eq(SystemConstants.ARTICLE_COMMENT.equals(type), Comment::getArticleId, articleId);
        //评论类型
        lqw.eq(Comment::getType, type);
        //根评论 rootId为-1
        lqw.eq(Comment::getRootId, SystemConstants.COMMENT_IS_ROOT);
        lqw.orderByDesc(Comment::getCreateTime);
        //分页查询
        Page<Comment> page = new Page<>(pageNum, pageSize);
        page(page, lqw);
        List<CommentVo> commentVoList = toCommentVoList(page.getRecords());

        //查询所有根评论对应的子评论集合，并且赋值
        commentVoList.forEach(commentVo -> {
            List<CommentVo> children = getChildren(commentVo.getId());
            commentVo.setChildren(children);
        });
        return ResponseResult.okResult(new PageVo(commentVoList, page.getTotal()));
    }

    @Transactional
    @Override
    public ResponseResult addComment(Comment comment) {
        // 若文章设置为不允许评论
        Article article = articleMapper.selectById(comment.getArticleId());
        if (comment.getType().equals(SystemConstants.ARTICLE_COMMENT)) {
            if (article.getIsComment().equals(SystemConstants.ARTICLE_COMMENT_NO)) {
                throw new SystemException(AppHttpCodeEnum.ARTICLE_COMMENT_NO);
            }
        }
        // 评论内容不能为空
        if (!StringUtils.hasText(comment.getContent())) {
            throw new SystemException(AppHttpCodeEnum.COMMENT_NOT_NULL);
        }
        // 不能回复自己
        if (comment.getToCommentUserId().equals(SecurityUtils.getUserId())) {
            throw new SystemException(AppHttpCodeEnum.COMMENT_NOT_SELF);
        }
        String address = "";
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getId, SecurityUtils.getUserId());
        lqw.select(User::getIpaddress);
        String ipAddress = userService.getOne(lqw).getIpaddress();
        try {
            IpInfo ipInfo = ip2regionSearcher.memorySearch(ipAddress);
            if (Objects.isNull(ipInfo)) {
                address = "未知";
            } else {
                address = ipInfo.getAddress();
                if (address.contains("中国")) {
                    address = address.split("中国")[1];
                }
            }
        } catch (Exception e) {
            address = "地址获取失败";
            e.printStackTrace();
        }
        // DFA算法过滤敏感词 matchType,1:最小匹配规则，2：最大匹配规则
        String content = sensitivewordFilter.replaceSensitiveWord(comment.getContent(), 2, "*");
        comment.setContent(content);
        comment.setAddress(address);
        save(comment);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult<PageVo> getAllComment(Integer pageNum, Integer pageSize, CommentListDto commentDto) {
        //分页查询
        LambdaQueryWrapper<Comment> lqw = new LambdaQueryWrapper();
        lqw.like(StringUtils.hasText(commentDto.getType()), Comment::getType, commentDto.getType());
        lqw.eq(StringUtils.hasText(commentDto.getStatus()), Comment::getStatus, commentDto.getStatus());
        lqw.eq(StringUtils.hasText(commentDto.getArticleId()), Comment::getArticleId, commentDto.getArticleId());
        lqw.orderByDesc(Comment::getCreateTime);
        Page<Comment> page = new Page<>();
        page.setCurrent(pageNum);
        page.setSize(pageSize);
        page(page, lqw);
        List<Comment> comments = page.getRecords();
        List<CommentListVo> commentListVos = BeanCopyUtils.copyBeanList(comments, CommentListVo.class);
        //封装数据返回
        PageVo pageVo = new PageVo(commentListVos, page.getTotal());
        return ResponseResult.okResult(pageVo);
    }

    /**
     * 根据根评论的Id查询所对应的子评论的集合
     *
     * @param rootId 根评论Id
     * @return
     */
    private List<CommentVo> getChildren(String rootId) {
        LambdaQueryWrapper<Comment> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Comment::getRootId, rootId);
        //评论必须是审核已通过的
        lqw.eq(Comment::getStatus, SystemConstants.COMMENT_NORMAL);
        lqw.orderByAsc(Comment::getCreateTime);
        List<Comment> children = list(lqw);
        List<CommentVo> childrenVoList = toCommentVoList(children);
        return childrenVoList;
    }

    private List<CommentVo> toCommentVoList(List<Comment> list) {
        List<CommentVo> commentVos = BeanCopyUtils.copyBeanList(list, CommentVo.class);
        //遍历vo集合
        commentVos.forEach(commentVo -> {
            //通过createBy查询用户昵称并赋值
            String userId = commentVo.getCreateBy();
            User user = userService.getById(userId);
            String nickName = "";
            String avatar = "";
            if (Objects.isNull(user)) {
                nickName = "用户已注销";
                avatar="https://zlw-blog.oss-cn-hangzhou.aliyuncs.com/2024/10/11/zhuxiao.jpg";
                commentVo.setUsername(nickName);
            } else {
                nickName = user.getNickName();
                avatar = user.getAvatar();
            }
            // 是否登录者的评论
//            if (StringUtils.hasText(SecurityUtils.getUserId())&&SecurityUtils.getUserId().equals(userId)){
//                commentVo.setIsMyself("1");
//            }else {
//                commentVo.setIsMyself("0");
//            }
            commentVo.setAvatar(avatar);
            commentVo.setUsername(nickName);
            //通过toCommentUserId查询用户的昵称并赋值
            //如果toCommentUserId不为-1才进行查询
            if (!commentVo.getToCommentUserId().equals(SystemConstants.COMMENT_IS_ROOT)) {
                String toCommentUserName = userService.getById(commentVo.getToCommentUserId()).getNickName();
                commentVo.setToCommentUserName(toCommentUserName);
            }
        });
        return commentVos;
    }
}

